﻿using System;
using System.Collections.Generic;

namespace CtpTrader.Logic.Core.Trade
{
    public class PositionManager
    {
        /// <summary>
        /// 单例模式对象
        /// </summary>
        private static PositionManager instance;

        /// <summary>
        /// 持仓列表
        /// </summary>
        public List<Position> Positions;

        /// <summary>
        /// 构造函数
        /// </summary>
        private PositionManager()
        {
            this.Positions = new List<Position>();
        }

        /// <summary>
        /// 获取单例模式对象
        /// </summary>
        /// <returns>单例模式对象</returns>
        public static PositionManager GetInstance()
        {
            if (instance == null)
                instance = new PositionManager();

            return instance;
        }

        /// <summary>
        /// 判断是否有持仓
        /// </summary>
        /// <param name="unit">持仓单位</param>
        /// <returns>如有则返回该持仓类，或者返回NULL</returns>
        public Position HasPosition(PositionUnit unit)
        {
            foreach (Position position in Positions)
            {
                if (position.Unit.Equals(unit))
                {
                    return position;
                }
            }

            return null;
        }

        /// <summary>
        /// 将持仓类加入持仓列表
        /// </summary>
        /// <param name="position">持仓类</param>
        public void Add(Position position)
        {
            if (position != null)
            {
                lock (this.Positions)
                {
                    this.Positions.Add(position);
                }
            }
        }

        /// <summary>
        /// 将持仓类移除持仓列表
        /// </summary>
        /// <param name="position">持仓类</param>
        public void Remove(Position position)
        { 
            lock(this.Positions)
            {
                this.Positions.Remove(position);
            }
        }
    }
}
